package com.cao.meet.mvp.model;

import android.content.Context;

import com.blankj.utilcode.util.StringUtils;
import com.cao.meet.mvp.contract.LoginContract;
import com.cao.meet.mvp.presenter.LoginPresenter;

import java.io.IOException;

import okhttp3.Authenticator;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;

/**
 * Created by ZKTH
 * Time ： 2018/12/20.10:05
 * data ：
 */

public class LoginModel implements LoginContract.Model {

    @Override
    public void login(final Context context, final String user_name, final String pass_woed) {
        loginSip("http://19.0.0.229:8080/webapi/sysinfo", user_name, pass_woed, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                login(context,user_name,pass_woed);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                LoginContract.Presenter login_presenter = new LoginPresenter();
                login_presenter.show_message(context,json);
            }
        });
    }

    /**
     * 登陆sip服务器
     *
     * @param internetAddress 服务器地址
     * @param userName        用户名
     * @param passWord        密码
     */
    public void loginSip(String internetAddress, String userName, String passWord, Callback callback) {
        //判断请求地址，userName，password是否为空
        if (!StringUtils.isEmpty(internetAddress) || !StringUtils.isEmpty(userName) || !StringUtils.isEmpty(passWord)) {
            //基于Http Basic做身份验证
            final String basic = Credentials.basic(userName,passWord);
            //创建OkHttpClient，并进行身份验证
            OkHttpClient mOkHttpClient = new OkHttpClient.Builder().authenticator(new Authenticator() {
                        @Override
                        public Request authenticate(Route route, Response response) throws IOException {
                            return response.request().newBuilder().header("Authorization", basic).build();
                        }
                    }).build();
                //创建Request对象
                Request mRequest = new Request.Builder().url(internetAddress).build();
            //使用OkHttp发起网络请求
            mOkHttpClient.newCall(mRequest).enqueue(callback);
        }
    }

}
